/**
 * 
 */
package com.yy.young.common.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

/**
 * SpringMVC文件上传工具类
 * @author wjy
 *
 */
public class UploadFileUtil {

	private static final String defaultPath = "\\";
	private static Logger logger = Logger.getLogger(UploadFileUtil.class);
	/**
	 * 上传文件(基础方法),其他工具方法统一调用该方法执行文件保存
	 * @param file
	 * @param path 文件存放的真实绝对路径,例如:c:\test\xx
	 * @return 文件保存的全路径
	 * @throws Exception
	 */
	public static String uploadFile(MultipartFile file,String path) throws Exception{
		if(!file.isEmpty()){
			String oldName = file.getOriginalFilename();//文件名
			String fileName = System.currentTimeMillis() + "_" + (int)(Math.random()*100) + "_" + oldName;//.substring(oldName.lastIndexOf("."))
			String wholeName = path + defaultPath + fileName;
			logger.info("[文件上传工具] 文件保存全路径: "+wholeName);
			try {
				file.transferTo(new File(wholeName));
			} catch (IllegalStateException e) {
				logger.error("[文件上传出错!]",e);
				e.printStackTrace();
				throw new Exception("文件上传异常:IllegalStateException");
			} catch (IOException e) {
				logger.error("[文件上传出错!]",e);
				e.printStackTrace();
				throw new Exception("文件上传异常:IOException");
			}
			return wholeName;
		}else{
			return null;
		}
	}
	/**
	 * 多上传文件
	 * @param files
	 * @param path 文件存放的真实绝对路径,例如:c:\test\xx
	 * @throws Exception
	 */
	public static String[] uploadFiles(MultipartFile[] files,String path) throws Exception{
		List<String> list = new ArrayList<String>();
		for(MultipartFile file : files){
			if(!file.isEmpty()){
				list.add(uploadFile(file,path));
			}
		}
		return (list != null && list.size() > 0) ? list.toArray(new String[]{}) : null;
	}
	/**
	 * 文件上传保存到服务器的项目目录下
	 * @param request
	 * @param file
	 * @param filePath 文件存放的路径,例如:/page/upload
	 * @throws Exception
	 */
	public static String uploadFile(HttpServletRequest request,MultipartFile file,String filePath) throws Exception{
		//项目根路径
    	String rootPath = request.getSession().getServletContext().getRealPath("");
    	return uploadFile(file,rootPath + filePath);
	}
	/**
	 * 多文件上传保存到服务器的项目目录下
	 * @param request
	 * @param file
	 * @param filePath 文件存放的路径,例如:/page/upload
	 * @throws Exception
	 */
	public static String[] uploadFiles(HttpServletRequest request,MultipartFile[] files,String filePath) throws Exception{
		//项目根路径
    	String rootPath = request.getSession().getServletContext().getRealPath("");
    	return uploadFiles(files,rootPath + filePath);
	}
	
}
